﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using spk_eAuction.Classes;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
namespace spk_eAuction.Paypal
{
    public partial class OrderConfirmPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string payType;
            if (Request.QueryString["status"] != null)
            {
                if (Request.QueryString["status"] == "success")
                {
                    if (Session["payment_amt"] != null)
                    {
                        NVPAPICaller test = new NVPAPICaller();

                        string retMsg = "";
                        string token = "";
                        string finalPaymentAmount = "";
                        string payerId = "";
                        NVPCodec decoder = null;

                        token = Request.QueryString["token"];
                        payerId = Request.QueryString["PayerID"];
                        finalPaymentAmount = Session["payment_amt"].ToString();

                        bool ret = test.ConfirmPayment(finalPaymentAmount, token, payerId, ref decoder, ref retMsg);
                        if (ret)
                        {
                            // Unique transaction ID of the payment. Note:  If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization & Capture APIs. 
                            string transactionId = decoder["TRANSACTIONID"];

                            // The type of transaction Possible values: l  cart l  express-checkout 
                            string transactionType = decoder["TRANSACTIONTYPE"];

                            // Indicates whether the payment is instant or delayed. Possible values: l  none l  echeck l  instant 
                            string paymentType = decoder["PAYMENTTYPE"];

                            // Time/date stamp of payment
                            string orderTime = decoder["ORDERTIME"];

                            // The final amount charged, including any shipping and taxes from your Merchant Profile.
                            string amt = decoder["AMT"];

                            // A three-character currency code for one of the currencies listed in PayPay-Supported Transactional Currencies. Default: USD.    
                            string currencyCode = decoder["CURRENCYCODE"];

                            // PayPal fee amount charged for the transaction    
                            string feeAmt = decoder["FEEAMT"];

                            // Amount deposited in your PayPal account after a currency conversion.    
                            string settleAmt = decoder["SETTLEAMT"];

                            // Tax charged on the transaction.    
                            string taxAmt = decoder["TAXAMT"];
                            //' Exchange rate if a currency conversion occurred. Relevant only if your are billing in their non-primary currency. If 
                            string exchangeRate = decoder["EXCHANGERATE"];
                            string firstName = decoder["L_CURRENCYCODEn"];
                            //                        Response.Write(firstName + "</br>" + transactionId + "</br>" + transactionType + "</br>" + paymentType + "</br>");
                        }
                        else
                        {
                            Response.Redirect("~/Paypal/APIError.aspx?" + retMsg);
                        }
                    }
                    // ----- Show details

                    MultiView1.SetActiveView(ViewError);
                    if (HttpContext.Current.Session["payment_type"] != null)
                        payType = HttpContext.Current.Session["payment_type"].ToString();
                    else
                        return;
                    // COINS
                    if (payType.Equals("coins"))
                    {
                        MultiView1.SetActiveView(ViewCoins);
                        LabelCoins.Text = Resources.OrderConfirmPage.aspx.LabelCoins_Text;
                        ShowOrderConfirm("coins");
                    }
                    // PRODUCTS
                    else if (payType.Equals("products"))
                    {
                        // prodocts -> resources
                        MultiView1.SetActiveView(ViewProducts);
                    }
                    FreeSession();
                    // ----- end Show details

                    //string address = "";
                    //ret = test.GetShippingDetails(token, ref payerId, ref address, ref retMsg);
                    //if (ret)
                    //{
                    //    Label1.Text = address;
                    //}
                    //else
                    //{
                    //    Response.Redirect("~/Paypal/APIError.aspx?" + retMsg);
                    //}
                }
                return;
            }

            // if error
            MultiView1.SetActiveView(ViewError);
            if (HttpContext.Current.Session["payment_type"] != null)
                payType = HttpContext.Current.Session["payment_type"].ToString();
            else
                return;
            if (payType.Equals("coins"))
            {
                LabelError.Text = Resources.OrderConfirmPage.aspx.LabelError_Coins;
                HyperLinkReturn.Text = Resources.OrderConfirmPage.aspx.HyperLinkReturn_Text;
                HyperLinkReturn.NavigateUrl = Resources.OrderConfirmPage.aspx.HyperLinkReturn_NavigateUrl_Coins;
            }
            else if (payType.Equals("products"))
            {
                // prodocts -> resources
                LabelError.Text = Resources.OrderConfirmPage.aspx.LabelError_Products;
                HyperLinkReturn.Text = Resources.OrderConfirmPage.aspx.HyperLinkReturn_Text;
                HyperLinkReturn.NavigateUrl = Resources.OrderConfirmPage.aspx.HyperLinkReturn_NavigateUrl_Products;
            }
        }

        void ShowOrderConfirm(string payType)
        {
            
            int count;
            if (payType.Equals("coins"))
            {
                GridViewCoins = HttpContext.Current.Session["shoppingcart"] as GridView;

                // Insert into Orders
                SqlParameter _param = new SqlParameter("@UserID", SqlDbType.UniqueIdentifier);
                _param.Value = Membership.GetUser().ProviderUserKey;
                count = DataAccess.ExecuteProcNonQuery("SP_Orders_Insert", _param);
                if (count <= 0)
                    Response.Write(String.Format("<script> alert('The order is not inserted'); </script>"));

                foreach (GridViewRow row in GridViewCoins.Rows)
                {
                    CheckBox CheckBox1 = row.FindControl("CheckBox1") as CheckBox;
                    HiddenField HiddenField1 = row.FindControl("HiddenField1") as HiddenField;
                    if (CheckBox1 != null)
                        if (!CheckBox1.Checked)
                            row.Visible = false;
                        else
                        {
                            if (Membership.GetUser().IsOnline)
                            {
                                SqlParameter[] _params = new[]{
                                    new SqlParameter("@UserID", SqlDbType.UniqueIdentifier),
                                    new SqlParameter("@ProductID", SqlDbType.Int)
                                };
                                _params[0].Value = Membership.GetUser().ProviderUserKey;
                                _params[1].Value = HiddenField1.Value;
                                
                                // Update AuctionAccount
                                count = DataAccess.ExecuteProcNonQuery("SP_Coins_Update", _params);
                                if(count <= 0)
                                    Response.Write(String.Format("<script> alert('{0} is not updated to AuctionAccount'); </script>", HiddenField1.Value));
                                
                                // Insert OrderDetails
                                count = DataAccess.ExecuteProcNonQuery("SP_OrderDetails", new SqlParameter("@ProductID", HiddenField1.Value));
                                if (count <= 0)
                                    Response.Write(String.Format("<script> alert('Cannot insert product {0} into OrderDetails'); </script>", HiddenField1.Value));
                            }
                            else
                                Response.Write("<script> alert('User has not logged in'); </script>");
                        }
                }
                GridViewCoins.DataBind();
            }
            else if (payType.Equals("products"))
            {

            }

        }

        void FreeSession()
        {
            HttpContext.Current.Session["payment_type"] = null;
            HttpContext.Current.Session["shoppingcart"] = null;
            HttpContext.Current.Session["payment_amt"] = null;
        }
    }
}